/*************************************************************************
 Copyright (C) Unpublished Unis Software, Inc. All rights reserved.
 Unis Software, Inc., Confidential and Proprietary.

 This software is subject to copyright protection
 under the laws of the Public of China and other countries.

 Unless otherwise explicitly stated, this software is provided
 by Unis "AS IS".
 *************************************************************************/
package com.unis.common.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

/**
 * @author CSJ (email:raulcsj@163.com)
 * @since 2012-11-8
 */
public final class WebUtil {
    private static final String PAGESTART = "start";
    private static final String PAGELIMIT = "limit";

    private WebUtil() {}

    /****************************************
     * 获取请求参数hashMap
     * 
     * @param request
     * @return map
     ****************************************/
    @SuppressWarnings("all")
    public static final Map<String, Object> getParamsMapFromRequest(HttpServletRequest request) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        Map reqParamMap = request.getParameterMap();
        Set<Map.Entry<String, Object>> entitySet = reqParamMap.entrySet();
        for (Map.Entry<String, Object> entry : entitySet) {
            String value = ((String[]) entry.getValue())[0];
            if (!PAGESTART.equals(entry.getKey()) || !PAGELIMIT.equals(entry.getKey())) {
                paramMap.put(entry.getKey(), value);
            }
        }
        // 处理分页
        String start = request.getParameter(PAGESTART);
        String limit = request.getParameter(PAGELIMIT);
        if (StringUtils.isNotEmpty(start) && StringUtils.isNotEmpty(limit)) {
            paramMap.put(PAGESTART, start);
            paramMap.put(PAGELIMIT, Integer.valueOf(start) + Integer.valueOf(limit));
        }
        return paramMap;
    }

    /****************************************
     * 判断是否为Ajax请求
     * 
     * @param request
     * @return
     ****************************************/
    public static final boolean isAjax(HttpServletRequest request) {
        return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
    }
}
